/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.EJB;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.MDoctor;
import entity.MHospital;
import entity.MMapHospitalDoctor;
import session.MDoctorFacade;
import session.MHospitalFacade;
import session.MMapHospitalDoctorFacade;

import util.jQgrid.JQGridFormatterUtil;
import util.jQgrid.JQGridRow;
import validate.Validator;

/**
 *
 * @author CHANWUT
 */
@WebServlet(name = "PrototypeController",
loadOnStartup = 1,
urlPatterns = {"/jQueryUi",
    "/jQueryForm",
    "/jQueryGrid",
    "/jQueryGrid/getNormalGridData",
    "/jQueryGridComplex",
    "/jQueryGrid/getComplexGridData",
    "/jQuerySearch",
    "/jQueryGrid/searchGridData"})
public class PrototypeController extends HttpServlet {

    private String sampleServletContext;
    @EJB
    private MHospitalFacade mHospitalFacade;
    @EJB
    private MDoctorFacade mDoctorFacade;
    @EJB
    private MMapHospitalDoctorFacade mMapHospitalDoctorFacade;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        super.init(servletConfig);

        // initialize servlet with configuration information
        sampleServletContext = servletConfig.getServletContext().getInitParameter("sampleServletContext");
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        // if category page is requested
        if (userPath.equals("/jQueryUi")) {
            userPath = "/jQueryUi";
        } else if (userPath.equals("/jQueryForm")) {
            userPath = "/jQueryForm";
        } else if (userPath.equals("/jQueryGrid")) {
            userPath = "/jQueryGrid";
        } else if (userPath.equals("/jQueryGridComplex")) {
            userPath = "/jQueryGridComplex";
        } else if (userPath.equals("/jQuerySearch")) {
            userPath = "/jQuerySearch";
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view/prototype" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as
        // 8-bit Unicode (e.g., for Czech characters)
        Boolean isDispatcher = true; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();
        Validator validator = new Validator();

        if (userPath.equals("/jQueryGrid/getNormalGridData")) {
            response.setContentType("text/json");
            PrintWriter out = response.getWriter();
            List<MHospital> lMHospital;
            Set s;
            List<String> orderedPropertyNames;
            String strJson = "";
            try {
                //Query Java Object
                lMHospital = mHospitalFacade.findAll();
                //Use HashSet
                s = new HashSet();
                s.addAll(lMHospital);

                //Specify field/property names
                orderedPropertyNames = new ArrayList<String>();
                orderedPropertyNames.add("ID");
                orderedPropertyNames.add("Name");

                strJson = JQGridFormatterUtil.getJSON(1, lMHospital.size(), s, orderedPropertyNames);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lMHospital = null;
                s = null;
                orderedPropertyNames = null;
                strJson = null;
            }

            isDispatcher = false;
        } else if (userPath.equals("/jQueryGrid/getComplexGridData")) {
            response.setContentType("text/json");
            PrintWriter out = response.getWriter();
            List<MMapHospitalDoctor> lMMapHospitalDoctor;
            List rows;
            JQGridRow row;
            List cells;
            String strJson = "";
            try {
                //Query Java Object
                lMMapHospitalDoctor = mMapHospitalDoctorFacade.findAll();
                //Use List rows
                rows = new ArrayList();
                if (!lMMapHospitalDoctor.isEmpty()) {
                    for (MMapHospitalDoctor obj : lMMapHospitalDoctor) {
                        row = new JQGridRow();
                        row.setId(obj.getId());

                        cells = new ArrayList();
                        cells.add(obj.getId().toString());
                        cells.add(obj.getMDoctor().getName());
                        cells.add(obj.getMHospital().getName());

                        row.setCell(cells);
                        rows.add(row);
                    }
                }

                strJson = JQGridFormatterUtil.getJSON(1, lMMapHospitalDoctor.size(), rows);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lMMapHospitalDoctor = null;
                rows = null;
                row = null;
                cells = null;
                strJson = null;
            }

            isDispatcher = false;
        } else if (userPath.equals("/jQueryGrid/searchGridData")) {
            response.setContentType("text/json");
            String qstr_examp = request.getParameter("q"); // query number

            String qstr_page = request.getParameter("page"); // get the requested page
            String qstr_limit = request.getParameter("rows"); // get how many rows we want to have into the grid
            String qstr_sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
            String qstr_sord = request.getParameter("sord"); // get the direction

            if(!qstr_sidx.isEmpty()) qstr_sidx = "1";

            String qstr_txtName = "";
            if(request.getParameter("txtName_mask") != null)
                    qstr_txtName = request.getParameter("txtName_mask");
            else
                    qstr_txtName = "";

            PrintWriter out = response.getWriter();
            List<MMapHospitalDoctor> lMMapHospitalDoctor;
            List rows;
            JQGridRow row;
            List cells;
            String strJson = "";
            try {
                //Query Java Object
                lMMapHospitalDoctor = mMapHospitalDoctorFacade.findAll();
                //Use List rows
                rows = new ArrayList();
                if (!lMMapHospitalDoctor.isEmpty()) {
                    for (MMapHospitalDoctor obj : lMMapHospitalDoctor) {
                        row = new JQGridRow();
                        row.setId(obj.getId());

                        cells = new ArrayList();
                        cells.add(obj.getId().toString());
                        cells.add(obj.getMDoctor().getName());
                        cells.add(obj.getMHospital().getName());

                        row.setCell(cells);
                        rows.add(row);
                    }
                }

                strJson = JQGridFormatterUtil.getJSON(1, lMMapHospitalDoctor.size(), rows);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lMMapHospitalDoctor = null;
                rows = null;
                row = null;
                cells = null;
                strJson = null;
            }

            isDispatcher = false;
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view/prototype" + userPath + ".jsp";

        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }
    }
}
